﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using Spotless.Services;

namespace SpotlessWeb.Helpers
{
    public static class SortExpressionHelper
    {
        /*public static SortExpression<TModel> SortExpression<TEnumerable, TModel>(this HtmlHelper<TEnumerable> htmlHelper)
            where TEnumerable : IEnumerable<TModel>
            where TModel : class
        {
            return new SortExpression<TModel>();
        }*/

        public static MvcHtmlString ColumnHeader<TModel>(this HtmlHelper htmlHelper, string text, SortExpression<TModel> sortExpression)
            where TModel : class
        {
            if (sortExpression != null)
            {
                var routeData = new RouteValueDictionary();
                foreach (var item in htmlHelper.ViewContext.HttpContext.Request.QueryString.AllKeys)
                {
                    routeData.Add(item, htmlHelper.ViewContext.HttpContext.Request.QueryString[item]);
                }
                string currentExpression = null;
                if (routeData.ContainsKey("sort"))
                {
                    currentExpression = (string)routeData["sort"];
                    routeData.Remove("sort");
                }

                var normalExpression = sortExpression.ToString();
                var reverseExpression = sortExpression.ToReverseString();

                var htmlAttributes = new Dictionary<string, object>();

                if (currentExpression == normalExpression)
                {
                    routeData["sort"] = reverseExpression;
                    htmlAttributes["class"] = "sortLinkAsc";

                }
                else if (currentExpression == reverseExpression)
                {
                    routeData["sort"] = normalExpression;
                    htmlAttributes["class"] = "sortLinkDesc";
                }
                else
                {
                    routeData["sort"] = normalExpression;
                }
                return htmlHelper.ActionLink(text, (string)null, (string)null, routeData, htmlAttributes);
            }
            else
            {
                return MvcHtmlString.Create(text);
            }
        }
    }
}
